<?php

namespace Home\Controller;


use Home\Service\WordpressSyncerService;
use Org\Util\Date;
use Org\Util\String;

class DocController extends BaseController
{
    const HISTORY_SIZE = 50;

    public function index()
    {
        $this->data_history_size = self::HISTORY_SIZE;
        $this->display();
    }

    public function mdeditor()
    {
        $this->display();
    }

    public function fetchall()
    {
        $page = I('post.page', 1, 'intval');
        $cat_id = I('post.cat_id', 0, 'intval');
        $search = I('post.search', array());
        $m = D('CmsDoc');

        $where = array('uid' => MEMBER_LOGINED_UID);
        if ($cat_id) {
            $where['cat_id'] = $cat_id;
        }
        if (!empty($search['keywords'])) {
            $where['title'] = array('LIKE', '%' . $search['keywords'] . '%');
        }

        $count = $m->where($where)->count();
        $list = $m->where($where)->order('update_time desc')->page($page, 10)->select();
        if (empty($list)) {
            $list = array();
        }

        $listFilterd = array();
        foreach ($list as &$r) {
            $listFilterd[] = array(
                'id' => $r['id'],
                'out_id' => $r['out_id'],
                'title' => $r['title'],
                'add_time' => date('Y-m-d H:i', $r['add_time']),
                'update_time' => date('Y-m-d H:i', $r['update_time']),
                'summary' => $r['summary']
            );
        }
        $this->ajaxReturn(array(
            'status' => 1,
            'hasMore' => $page * 10 < $count,
            'list' => $listFilterd
        ));

    }

    public function load()
    {
        $m = D('CmsDoc');
        $md = D('CmsDocData');

        $id = I('post.id', 0, 'intval');

        $one = $m->where(array('id' => $id, 'uid' => MEMBER_LOGINED_UID))->find();
        if (empty($one)) {
            $this->error('这个不是你的文档');
        }
        $oned = $md->where(array('doc_id' => $one['id']))->find();
        if (empty($oned)) {
            $this->error('文档正文没找到');
        }

        $wp_id = 0;
        if (tpx_config_get('wordpress_syncer_enable')) {
            $wp_id = WordpressSyncerService::get_wppostid_by_tpxdocid($one['id']);
        }

        $this->ajaxReturn(array(
            'status' => 1,
            'data' => array(
                'id' => $one['id'],
                'cat_id' => $one['cat_id'],
                'out_id' => $one['out_id'],
                'title' => $one['title'],
                'content' => $oned['content'],
                'wp_id' => $wp_id
            )
        ));
    }


    public function add()
    {
        $m = D('CmsDoc');
        $md = D('CmsDocData');
        $mc = D('CmsDocCat');

        $cat_id = I('post.cat_id', 0, 'intval');
        $title = I('post.title', '', 'trim');
        $content = I('post.content', '', 'trim');

        if (empty($cat_id)) {
            $this->error('分类为空');
        }
        if (empty($title)) {
            $this->error('标题为空');
        }
        if (empty($content)) {
            $this->error('内容为空');
        }

        $cat = $mc->where(array('uid' => MEMBER_LOGINED_UID, 'id' => $cat_id))->find();
        if (empty($cat)) {
            $this->error('分类不存在');
        }

        $data = array();
        $data['uid'] = MEMBER_LOGINED_UID;
        $data['cat_id'] = $cat_id;
        $data['add_time'] = time();
        $data['update_time'] = time();
        $data['title'] = $title;
        $data['summary'] = msubstr($content,0,200);

        do {
            $data['out_id'] = String::randString(50);
            $exists = $m->where(array('out_id' => $data['out_id']))->find();
        } while (!empty($exists));

        $id = $m->add($data);
        $md->add(array('doc_id' => $id, 'content' => $content));
        $mc->where(array('id' => $cat_id))->setInc('doc_cnt', 1);

        $this->ajaxReturn(array(
            'status' => 1,
            'info' => 'ok',
            'data' => array(
                'id' => $id,
                'out_id' => $data['out_id']
            )
        ));

    }

    public function edit()
    {
        $m = D('CmsDoc');
        $md = D('CmsDocData');
        $mc = D('CmsDocCat');
        $mhd = D('CmsDocHistoryData');

        $id = I('post.id', 0, 'intval');
        $cat_id = I('post.cat_id', 0, 'intval');
        $title = I('post.title', '', 'trim');
        $content = I('post.content', '', 'trim');

        if (empty($cat_id)) {
            $this->error('分类为空');
        }
        if (empty($title)) {
            $this->error('标题为空');
        }
        if (empty($content)) {
            $this->error('内容为空');
        }

        $cat = $mc->where(array('uid' => MEMBER_LOGINED_UID, 'id' => $cat_id))->find();
        if (empty($cat)) {
            $this->error('分类不存在');
        }

        $one = $m->where(array('uid' => MEMBER_LOGINED_UID, 'id' => $id))->find();
        if (empty($one)) {
            $this->error('文档不存在');
        }

        $oned = $md->where(array('doc_id' => $id))->find();
        if (empty($oned)) {
            $this->error('文档正文不存在');
        }

        // 添加历史
        if ($content != $oned['content']) {
            $mhd->add(
                array(
                    'doc_id' => $id,
                    'update_time' => time(),
                    'content' => $oned['content']
                ));
            $ids = $mhd->field('id')->where(array('doc_id' => $id))->order('update_time desc')->page(2, self::HISTORY_SIZE)->select();
            //echo $mhd->getLastSql();
            if (!empty($ids)) {
                $idsArr = array();
                foreach ($ids as &$r) {
                    $idsArr[] = $r['id'];
                }
                $mhd->delete(join(',', $idsArr));
            }
        }

        $old_cat_id = $one['cat_id'];

        $one['cat_id'] = $cat_id;
        $one['title'] = $title;
        $one['update_time'] = time();
        $one['summary'] = msubstr($content,0,200);
        $m->save($one);

        $oned['content'] = $content;
        $md->save($oned);

        if ($old_cat_id != $cat_id) {
            $mc->where(array('id' => $old_cat_id))->setDec('doc_cnt', 1);
            $mc->where(array('id' => $cat_id))->setInc('doc_cnt', 1);
        }

        $this->ajaxReturn(array(
            'status' => 1,
            'info' => 'ok',
            'data' => array(
                'id' => $id,
                'out_id' => $one['out_id'],
                'update_time' => date('Y-m-h H:i')
            )
        ));
    }

    public function delete()
    {
        $m = D('CmsDoc');
        $md = D('CmsDocData');
        $mc = D('CmsDocCat');
        $mhd = D('CmsDocHistoryData');

        $id = I('post.id', 0, 'intval');

        $one = $m->where(array('uid' => MEMBER_LOGINED_UID, 'id' => $id))->find();
        if (empty($one)) {
            $this->error('文档不存在');
        }

        $oned = $md->where(array('doc_id' => $id))->find();
        if (empty($oned)) {
            $this->error('文档正文不存在');
        }

        $m->delete($id);
        $md->delete($oned['id']);

        // 删除历史
        $mhd->where(array('doc_id' => $id))->delete();

        $mc->where(array('id' => $one['cat_id']))->setDec('doc_cnt', 1);

        $this->ajaxReturn(array(
            'status' => 1,
            'info' => 'ok',
            'data' => $one
        ));
    }

    public function fetch_history()
    {
        $m = D('CmsDoc');
        $md = D('CmsDocData');
        $mhd = D('CmsDocHistoryData');

        $id = I('post.id', 0, 'intval');

        $one = $m->where(array('uid' => MEMBER_LOGINED_UID, 'id' => $id))->find();
        if (empty($one)) {
            $this->error('文档不存在');
        }

        $oned = $md->where(array('doc_id' => $one['id']))->find();
        if (empty($oned)) {
            $this->error('文档正文不存在');
        }

        $list = $mhd->where(array('doc_id' => $id))->order('update_time desc')->select();
        if (empty($list)) {
            $list = array();
        }

        $date = new Date(time());

        $listFilterd = array();

        $listFilterd[] = array(
            'id' => '0',
            'update_time' => '最新保存版本 （' . date('Y-m-d H:i:s', $one['update_time']) . '）',
            'content' => $oned['content']
        );

        foreach ($list as &$r) {
            $listFilterd[] = array(
                'id' => $r['id'],
                'update_time' => $date->timeDiff(intval($r['update_time'])) . ' ( ' . date('Y-m-d H:i:s', $r['update_time']) . ' ) ',
                'content' => $r['content']
            );
        }


        $this->ajaxReturn(array(
            'status' => 1,
            'list' => $listFilterd
        ));
    }

    public function upload_image()
    {


        // 上传说明：
        // 考虑到未来存储，上传的临时数据在_RUN/Temp（TEMP_PATH=./_RUN/Temp）
        // 添加成功后，所有数据传送到 data/*中
        // 注意data/中的所有数据都应该使用Storage驱动来操作，方便后期移植
        $config = array(

            // 上传图片配置项
            'imageActionName' => 'uploadimage',
            'imageFieldName' => 'editormd-image-file',
            'imageMaxSize' => C('USER_UPLOAD.IMAGE_MAX_SIZE'),
            'imageAllowFiles' => C('USER_UPLOAD.IMAGE_ALLOW_EXT'),
            'imageCompressEnable' => true,
            'imageCompressBorder' => 1600,
            'imageInsertAlign' => 'none',
            'imageUrlPrefix' => __ROOT__ . '/',
        );

        $ret = array(
            'success' => 0,
            'message' => '上传失败',
            'url' => ''
        );

        $up = new \Think\Upload ();
        $up->saveName = upload_temp_file_get();
        $up->replace = true;
        $up->subName = '';
        $up->rootPath = upload_temp_dir_get();

        if (!file_exists($up->rootPath)) {
            @mkdir($up->rootPath, 0777, true);
        }


        $upload_size_space = $this->_am->get('upload_space.space', 0);
        $one = D('MemberUpload')->table('__MEMBER_UPLOAD__ mu')->join('__DATA_FILES__ df ON df.id=mu.data_id')
            ->field('sum(df.filesize) as total')->where(array('mu.uid' => MEMBER_LOGINED_UID))->find();
        $upload_size_current = $one['total'];

        if ($upload_size_current < $upload_size_space) {

            $mapping = array(
                'uploadfile' => 'file',
                'uploadimage' => 'image',
                'uploadvideo' => 'video'
            );

            $up->maxSize = $config ['imageMaxSize'];

            foreach ($config ['imageAllowFiles'] as &$i) {
                $i = trim($i, '.');
            }
            $up->exts = $config ['imageAllowFiles'];

            if (!($info = $up->upload())) {
                $ret ['message'] = $up->getError();
            } else {

                $one = &$info [$config ['imageFieldName']];
                $savefile = upload_tempfile_save_storage('image', $up->rootPath . $one ['savepath'] . $one ['savename']);

                $file = query_storage_file('image', $savefile);
                if (!empty($file)) {
                    D('MemberUpload')->add(array(
                        'data_id' => $file['id'],
                        'uid' => MEMBER_LOGINED_UID
                    ));

                    $ret ['success'] = 1;
                    $ret['message'] = '上传成功';
                    $ret ['url'] = 'http://' . HTTP_HOST . __ROOT__ . '/data/image/' . $savefile;

                } else {
                    $ret['message'] = '保存到用户数据库失败';
                }

            }
        } else {
            $ret['message'] = '你已经使用了' . byte_format($upload_size_current) . ' / ' . byte_format($upload_size_space) . '的文件空间';
        }
        $this->ajaxReturn($ret);
    }


    public function fetch_wordpress_category()
    {
        if (!tpx_config_get('wordpress_syncer_enable')) {
            $this->error('Wordpress同步未开启');
        }
        $categorys = WordpressSyncerService::get_category();
        $this->ajaxReturn(array('status' => 1, 'data' => $categorys));
    }


    public function wordpress_publish()
    {
        if (!tpx_config_get('wordpress_syncer_enable')) {
            $this->error('Wordpress同步未开启');
        }

        $m = D('CmsDoc');
        $md = D('CmsDocData');

        $categorys = I('post.categorys', array());
        $id = I('post.id', 0, 'intval');
        if (empty($categorys)) {
            $this->error('分类为空');
        }

        $one = $m->where(array('uid' => MEMBER_LOGINED_UID, 'id' => $id))->find();
        if (empty($one)) {
            $this->error('文档不存在');
        }

        $oned = $md->where(array('doc_id' => $id))->find();
        if (empty($oned)) {
            $this->error('文档正文不存在');
        }

        $wp_uid = WordpressSyncerService::get_wpuid_by_tpxuid(MEMBER_LOGINED_UID);
        if (empty($wp_uid)) {
            $this->error('未找到对应的Wordpress用户UID');
        }

        $wp_post_id = WordpressSyncerService::get_wppostid_by_tpxdocid($id);
        if (!empty($wp_post_id)) {
            $this->error('该文档已在Wordpress中发布，不能重复发布');
        }


        $data = array();
        $data['post_author'] = $wp_uid;
        $data['post_date'] = date('Y-m-d H:i:s', time());
        $data['post_date_gmt'] = date('Y-m-d H:i:s', time());
        $data['post_content'] = $oned['content'];
        $data['post_title'] = $one['title'];
        //$data['post_excerpt'] = 'http://' . HTTP_HOST . __ROOT__ . '/' . (C('URL_MODEL') != 2 ? '?s=' : '') . '/r/download/out_id/' . $one['out_id'];
        $data['post_status'] = 'publish';
        $data['comment_status'] = 'open';
        $data['ping_status'] = 'open';
        $data['post_name'] = urlencode($one['title']);
        $data['post_modified'] = date('Y-m-d H:i:s', time());
        $data['post_modified_gmt'] = date('Y-m-d H:i:s', time());
        $data['post_type'] = 'post';


        $wpm = WordpressSyncerService::M('Posts');
        $wp_inserted_id = $wpm->add($data);
        WordpressSyncerService::set_categorys($wp_inserted_id, $categorys);

        D('WordpressSyncerDocMap')->add(array(
            'wp_id' => $wp_inserted_id,
            'doc_id' => $id
        ));

        WordpressSyncerService::M('Postmeta')->add(array(
            'post_id' => $wp_inserted_id,
            'meta_key' => '_beautymark_status',
            'meta_value' => '1'
        ));

        $this->ajaxReturn(array(
            'status' => 1,
            'data' => array(
                'wp_id' => $wp_inserted_id
            )
        ));

    }

    public function wordpress_sync()
    {
        if (!tpx_config_get('wordpress_syncer_enable')) {
            $this->error('Wordpress同步未开启');
        }

        $m = D('CmsDoc');
        $md = D('CmsDocData');
        $wpm = WordpressSyncerService::M('Posts');

        $id = I('post.id', 0, 'intval');

        $one = $m->where(array('uid' => MEMBER_LOGINED_UID, 'id' => $id))->find();
        if (empty($one)) {
            $this->error('文档不存在');
        }

        $oned = $md->where(array('doc_id' => $id))->find();
        if (empty($oned)) {
            $this->error('文档正文不存在');
        }

        $wp_uid = WordpressSyncerService::get_wpuid_by_tpxuid(MEMBER_LOGINED_UID);
        if (empty($wp_uid)) {
            $this->error('未找到对应的Wordpress用户UID');
        }

        $wp_post_id = WordpressSyncerService::get_wppostid_by_tpxdocid($id);
        if (empty($wp_post_id)) {
            $this->error('该文档不存在在Wordpress中，不能发布');
        }

        $onewp = $wpm->find($wp_post_id);

        if (empty($onewp)) {
            $this->error('Wordpress不存在ID为' . $wp_post_id . '的文档');
        }

        $onewp['ID'] = $wp_post_id;
        $onewp['post_content'] = $oned['content'];
        $onewp['post_title'] = $one['title'];
        //$onewp['post_excerpt'] = 'http://' . HTTP_HOST . __ROOT__ . '/' . (C('URL_MODEL') != 2 ? '?s=' : '') . '/r/download/out_id/' . $one['out_id'];
        $onewp['post_modified'] = date('Y-m-d H:i:s', time());
        $onewp['post_modified_gmt'] = date('Y-m-d H:i:s', time());

        $wpm->save($onewp);


        $this->ajaxReturn(array(
            'status' => 1,
        ));
    }

    public function wordpress_unlink()
    {
        if (!tpx_config_get('wordpress_syncer_enable')) {
            $this->error('Wordpress同步未开启');
        }

        $m = D('CmsDoc');
        $md = D('CmsDocData');

        $id = I('post.id', 0, 'intval');

        $one = $m->where(array('uid' => MEMBER_LOGINED_UID, 'id' => $id))->find();
        if (empty($one)) {
            $this->error('文档不存在');
        }

        $oned = $md->where(array('doc_id' => $id))->find();
        if (empty($oned)) {
            $this->error('文档正文不存在');
        }

        $wp_uid = WordpressSyncerService::get_wpuid_by_tpxuid(MEMBER_LOGINED_UID);
        if (empty($wp_uid)) {
            $this->error('未找到对应的Wordpress用户UID');
        }

        $wp_post_id = WordpressSyncerService::get_wppostid_by_tpxdocid($id);
        if (empty($wp_post_id)) {
            $this->error('该文档不存在Wordpress管理中，不能解除');
        }

        M('WordpressSyncerDocMap')
            ->where(array(
                'wp_id' => $wp_post_id,
                'doc_id' => $id
            ))
            ->delete();

        $this->ajaxReturn(array(
            'status' => 1,
        ));
    }


}